package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //将好友关系保存到双方的friend表中
    @Override
    public void save(Long userId, Long friendId) {
        //添加好友
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //1.1 判断好友关系是否存在
        if(!mongoTemplate.exists(query1, Friend.class)){
            //1.2 如果不存在，保存
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //判断好友的好友关系是否存在
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if(!mongoTemplate.exists(query1, Friend.class)) {
            //1.2 如果不存在，保存
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;
    }
}
